package cmd

import (
	"context"
	"fmt"
	"path"

	"github.com/chromedp/cdproto/cdp"
	"github.com/chromedp/chromedp"
	"github.com/chromedp/chromedp/device"
)

func (tr *TaskRunner) IterShop(itAction func(*TaskRunner)) *TaskRunner {
	const refererUrl = `https://www.dianping.com/search/keyword/1/0_牛太叔`
	shopUrls, err := tr.ReadLines("tmp/1_牛太叔_p1.txt")
	if err != nil {
		slog.Panicln("readFile err:", err)
	}
	for _, url := range shopUrls {
		fmt.Printf("processing shop:%s\n", url)
		tr.NavigateWithReferer(url, refererUrl)
		itAction(tr)
	}
	return tr
}

// obsolete
func (tr *TaskRunner) ScreenshotShopInfo() *TaskRunner {
	selShopName := `#basic-info > h1`
	selShopAddress := `#address`
	selRecommendDishes := `#shop-tabs > div.shop-tab-recommend.J-panel > ul > li`
	// #shop-tabs > div.shop-tab-recommend.J-panel > ul > li:nth-child(1) > p
	var url, shopID string
	var nodes []*cdp.Node
	tr.tasks = append(tr.tasks,
		chromedp.Location(&url), // shop detail url=> https://www.dianping.com/shop/k7M9KlVJp8xm9BOo
		chromedp.ActionFunc(func(ctx context.Context) error {
			// 从url提取
			shopID = path.Base(url)
			tr.shopInfo.ID = shopID
			return nil
		}),
		chromedp.Emulate(device.IPhone12Pro),
		IfPresent(
			selShopName,
			Sequence(
				// chromedp.WaitVisible(selShopName, chromedp.ByID),
				chromedp.Screenshot(selShopName, &tr.screenShotBuf, chromedp.NodeVisible, chromedp.ByID),
				chromedp.ActionFunc(func(ctx context.Context) error {
					tmpFile := fmt.Sprintf(`tmp/shop_%s/name.png`, shopID)
					if err := tr._dumpPicBytesToFile(tr.screenShotBuf, tmpFile); err != nil {
						return err
					}
					tr.ocr.SetImage(tmpFile)
					text, err := tr.ocr.Text()
					if err != nil {
						return err
					}
					text = RemoveEmtpy(text)
					slog.Infof("shop-name:%s", text)
					tr.shopInfo.Name = text
					return nil
				}),
			),
		),
		IfPresent(
			selShopAddress,
			Sequence(
				chromedp.WaitVisible(selShopAddress, chromedp.ByID),
				chromedp.Screenshot(selShopAddress, &tr.screenShotBuf, chromedp.NodeVisible, chromedp.ByID),
				chromedp.ActionFunc(func(ctx context.Context) error {
					tmpFile := fmt.Sprintf(`tmp/shop_%s/address.png`, shopID)
					if err := tr._dumpPicBytesToFile(tr.screenShotBuf, tmpFile); err != nil {
						return err
					}
					tr.ocr.SetImage(tmpFile)
					text, err := tr.ocr.Text()
					if err != nil {
						return err
					}
					text = RemoveEmtpy(text)
					slog.Infof("shop-address:%s", text)
					tr.shopInfo.Address = text
					return nil
				}),
			),
		),
		IfPresent(
			selRecommendDishes, // sel for check if is presented
			// true-part
			Sequence(
				chromedp.WaitVisible(selRecommendDishes, chromedp.ByQueryAll),
				chromedp.Nodes(selRecommendDishes, &nodes, chromedp.ByQueryAll),
				// 推荐菜
				chromedp.ActionFunc(func(ctx context.Context) error {
					if len(nodes) == 0 {
						slog.Info("no recommend dishes")
						return nil
					}
					var moreBtns []*cdp.Node
					if err := chromedp.Run(ctx, chromedp.Nodes(`#shop-tabs > div.shop-tab-recommend.J-panel > a.more.unfold.J-more`, &moreBtns, chromedp.AtLeast(0))); err != nil {
						return err
					}
					slog.Infof("has (%d) dishes...", len(nodes))
					if len(moreBtns) > 0 {
						nodes = nodes[:14]
					}
					slog.Infof("cut recommend dishes to (%d)...", len(nodes))
					for i := range nodes {
						idx := i + 1
						var buf []byte
						if err := chromedp.Run(ctx,
							chromedp.Screenshot(fmt.Sprintf("#shop-tabs > div.shop-tab-recommend.J-panel > ul > li:nth-child(%d) > p", idx), &buf, chromedp.NodeVisible, chromedp.ByID),
							chromedp.ActionFunc(func(ctx context.Context) error {
								tmpFile := fmt.Sprintf(`tmp/shop_%s/recommand-dish-%d.png`, shopID, idx)
								if err := tr._dumpPicBytesToFile(buf, tmpFile); err != nil {
									return err
								}
								tr.ocr.SetImage(tmpFile)
								text, err := tr.ocr.Text()
								if err != nil {
									return err
								}
								text = RemoveEmtpy(text)
								slog.Infof("recommand-dish-%d.ocr-name:%s", idx, text)
								tr.shopInfo.RecommandDishes = append(tr.shopInfo.RecommandDishes, text)
								return nil
							}),
						); err != nil {
							return err
						}
					}
					return nil
				}),
			),
		),
	)
	return tr
}

// obsolete
func (tr *TaskRunner) ScreenshotElement(sel, file string) *TaskRunner {
	var buf []byte
	tr.tasks = append(tr.tasks,
		chromedp.WaitVisible(sel, chromedp.ByID),
		chromedp.Screenshot(sel, &buf, chromedp.NodeVisible, chromedp.ByID),
		chromedp.ActionFunc(func(ctx context.Context) error {
			tr._dumpPicBytesToFile(buf, file)
			return nil
		}),
	)
	return tr
}
